<template>
  <view class="container">
    <!-- 主标签栏（最顶部） -->
    <view class="main-tabs">
      <view
        v-for="tab in mainTabs"
        :key="tab.key"
        :class="['main-tab-item', { active: activeMainTab === tab.key }]"
        @click="handleMainTabChange(tab.key)"
      >
        {{ tab.label }}
      </view>
    </view>

    <!-- 仅服务订单时显示4个按钮tabs和内容 -->
    <view v-if="activeMainTab === 'service'">
      <!-- Tabs栏 -->
      <view class="tabs">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index" 
          :class="['tab-item', { active: activeTab === index }]"
          @click="activeTab = index"
        >
          {{ tab.label }}
        </view>
      </view>

      <!-- 内容区域 -->
      <view class="content">
        <view v-if="activeTab === 0">
          <view v-for="order in allOrders" :key="order.orderId" class="order-item" @click="goToOrderDetail(order)">
            <view class="order-info">
              <text class="order-title">订单号: {{ order.dispatchNumber }}</text>
              <text class="order-detail">服务名称: {{ order.serviceName }}  服务时间:{{ order.serviceStartTime }}-{{ order.serviceEndTime }}</text>
              <text class="order-detail">服务日期: {{ order.appointmentStartDate }}-{{ order.appointmentEndDate }}</text>
              <text class="order-status">状态: {{ formatStatus(order.status) }}</text>
            </view>
          </view>
        </view>
        <view v-if="activeTab === 1">
          <view v-for="order in pendingServiceOrders" :key="order.orderId" class="order-item" @click="goToOrderDetail(order)">
            <view class="order-info">
              <text class="order-title">订单号: {{ order.dispatchNumber }}</text>
              <text class="order-detail">服务名称: {{ order.serviceName }}  服务时间:{{ order.serviceStartTime }}-{{ order.serviceEndTime }}</text>
              <text class="order-detail">服务日期: {{ order.appointmentStartDate }}-{{ order.appointmentEndDate }}</text>
              <text class="order-status">状态: {{ formatStatus(order.status) }}</text>
            </view>
          </view>
        </view>
        <view v-if="activeTab === 2">
          <view v-for="order in inServiceOrders" :key="order.orderId" class="order-item" @click="goToOrderDetail(order)">
            <view class="order-info">
              <text class="order-title">订单号: {{ order.dispatchNumber }}</text>
              <text class="order-detail">服务名称: {{ order.serviceName }}  服务时间:{{ order.serviceStartTime }}-{{ order.serviceEndTime }}</text>
              <text class="order-detail">服务日期: {{ order.appointmentStartDate }}-{{ order.appointmentEndDate }}</text>
              <text class="order-status">状态: {{ formatStatus(order.status) }}</text>
            </view>
          </view>
        </view>
        <view v-if="activeTab === 3">
          <view v-for="order in settledOrders" :key="order.orderId" class="order-item" @click="goToOrderDetail(order)">
            <view class="order-info">
              <text class="order-title">订单号: {{ order.dispatchNumber }}</text>
              <text class="order-detail">服务名称: {{ order.serviceName }}  服务时间:{{ order.serviceStartTime }}-{{ order.serviceEndTime }}</text>
              <text class="order-detail">服务日期: {{ order.appointmentStartDate }}-{{ order.appointmentEndDate }}</text>
              <text class="order-status">状态: {{ formatStatus(order.status) }}</text>
              <view class="evaluation-button" @click="goToEvaluation(order.orderId, order.caregiverId)">
                <text>评价</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品订单内容 -->
    <view v-else>
      <view class="content">
        <view v-if="productOrders.length === 0" class="order-empty">暂无商品订单</view>
        <view v-for="order in productOrders.filter(o => o.status !== 'PENDING')" :key="order.id" class="order-item" @click="goToProductOrderDetail(order)">
          <view class="order-info">
            <text class="order-title">订单号: {{ order.outTradeNo }}</text>
            <text class="order-detail">商品清单: {{ order.productList }}</text>
            <text class="order-detail">收货人: {{ order.name }}（{{ order.phone }}）</text>
            <text class="order-detail">收货地址: {{ order.address }}</text>
            <text class="order-detail">金额: ¥{{ order.amount }}</text>
            <text class="order-status">状态: {{ formatProductOrderStatus(order.status) }}</text>
          </view>
        </view>
        
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getCustomerOrderDetail } from '@/api/system/login';
import { getUserOrderList } from '@/api/wxlogin/wxlogin';


const tabs = ref([
  { label: '全部订单' },
  { label: '待服务' },
  { label: '服务中' },
  { label: '评价中心' }
]);

const activeTab = ref(0);
const allOrders = ref([]);
const pendingServiceOrders = ref([]);
const inServiceOrders = ref([]);
const settledOrders = ref([]);
const phoneNumber =ref([]);

// 主标签
const mainTabs = ref([
  { label: '服务订单', key: 'service' },
  { label: '商品订单', key: 'product' }
]);
const activeMainTab = ref('service');

// 商品订单数据
const productOrders = ref([]);

onLoad(async (options) => {
  // 检查登录状态
  const isLoggedIn = uni.getStorageSync('isLoggedIn');
  if (!isLoggedIn) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      success: () => {
        setTimeout(() => {
          uni.redirectTo({ url: '/pages/customer-platform/index/my' });
        }, 1500);
      }
    });
    return;
  }

  // 检查手机号缓存
  const phone = uni.getStorageSync('phoneNumber');
  if (!phone) {
    uni.showModal({
      title: '提示',
      content: '未找到用户信息，请重新登录',
      showCancel: false,
      success: () => {
        uni.removeStorageSync('isLoggedIn');
        uni.redirectTo({ url: '/pages/customer-platform/index/my' });
      }
    });
    return;
  }

  if (options.tab) {
    activeTab.value = parseInt(options.tab);
  }
  await fetchOrders(phone);
});

const fetchOrders = async (phoneNumber) => {
  try {
    const response = await getCustomerOrderDetail({ patientContact: phoneNumber });
    if (response.code === 200) {
      allOrders.value = response.data.list;
      pendingServiceOrders.value = response.data.list.filter(order => order.status === 'PENDING_SETTLE'||order.status === 'PENDING_CONFIRM');
      inServiceOrders.value = response.data.list.filter(order => order.status === 'IN_SERVICE');
      settledOrders.value = response.data.list.filter(order => order.status === 'SETTLED');
    }
  } catch (error) {
    console.error('获取订单数据失败:', error);
    uni.showToast({
      title: '获取订单失败',
      icon: 'none'
    });
  }
};

const fetchProductOrders = async () => {
  const wxUserId = uni.getStorageSync('userId');
  if (!wxUserId) return;
  try {
    const res = await getUserOrderList({ wxUserId });
    if (res.code === 200) {
      productOrders.value = res.data || [];
    }
  } catch (err) {
    uni.showToast({ title: '获取商品订单失败', icon: 'none' });
  }
};

const formatStatus = (status) => {
  const statusMap = {
    'PENDING_CONFIRM': '待确认',
    'PENDING_SETTLE': '待结算',
    'IN_SERVICE': '服务中',
    'SETTLED': '已结算'
  };
  return statusMap[status] || status;
};

const formatProductOrderStatus = (status) => {
  const map = {
    'PENDING': '待支付',
    'PAID': '待发货',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return map[status] || status
};

const goToEvaluation = (orderId, caregiverId) => {
  uni.navigateTo({
    url: `/pages/customer-platform/evaluation/index?orderId=${orderId}&caregiverId=${caregiverId}`,
  });
};

const goToOrderDetail = (order) => {
  uni.navigateTo({
    url: `/pages/customer-platform/order/detail?data=${encodeURIComponent(JSON.stringify(order))}`
  });
};

const goToProductOrderDetail = (order) => {
  uni.navigateTo({
    url: `/pages/customer-platform/order/productDetail?data=${encodeURIComponent(JSON.stringify(order))}`
  });
};

const handleMainTabChange = (key) => {
  activeMainTab.value = key;
  if (key === 'product') {
    fetchProductOrders();
  }
};
onMounted(async () => {
  const res = await getNoticeList()
  if (res.code === 200 && Array.isArray(res.data)) {
    // 例如只取type2
    const type2Notice = res.data.find(item => item.noticeId === 3)
    if (type2Notice) {
      noticeContent.value = type2Notice.notice
    }
  }
})
</script>

<style scoped lang="scss">
.container {
  padding: 32rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.tabs {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
  gap: 4rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

  .tab-item {
    flex: 1;
    padding: 16rpx;
    background-color: #f5f5f5;
    color: #333;
    border-radius: 8rpx;
    font-size: 28rpx;
    height: 60rpx;
    line-height: 60rpx;
    margin: 0;
    text-align: center;
    transition: background-color 0.3s ease;

    &.active {
      background-color: #ffcc00;
      color: #fff;
      font-weight: bold;
    }
  }
}

.main-tabs {
  display: flex;
  margin-bottom: 16rpx;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;

  .main-tab-item {
    flex: 1;
    text-align: center;
    padding: 20rpx 0;
    font-size: 30rpx;
    color: #666;
    background: #f5f5f5;

    &.active {
      background: #ffcc00;
      color: #fff;
      font-weight: bold;
    }
  }
}

.content {
  padding: 20rpx;
  position: relative;
}

.order-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 16rpx;
  margin-bottom: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.order-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.order-detail {
  font-size: 24rpx;
  color: #666;
}

.order-status {
  font-size: 24rpx;
  color: #ffcc00;
  font-weight: bold;
}

.evaluation-button {
  position: absolute;
  bottom: 16rpx;
  right: 16rpx;
  background-color: #ffcc00;
  color: #fff;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.order-empty {
  text-align: center;
  color: #999;
  margin: 40rpx 0;
}
</style>
